<script setup>
import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox,ElLoading  } from 'element-plus';
import {getMemberLevelList,getMemberCount,getMemberLayeringList } from '@/api/Member/index.js'
import { getTaskDetail,releaseDetPage } from '@/api/Marketing/coupon.js'
import TopBar from '@/components/Topbar/index.vue';
import getRules from "@/validUtils";
const route = useRoute();
const router = useRouter();
const instance = getCurrentInstance();
const topbarRef = ref(null);

const backValue = ref('CouponOrganizeIndex');
const tabName = ref("查看发放");

const formRef = ref(null);
const storeList = ref([]);

const form = ref({
    name:"",
    remark:"",
    sendType:0,
    sendObject:0,
    isMemberType:false, 
    memberLevel:[],
    memberlayer:[],
    memberphone:"",
    sendWay:0,
    useTimeValue:"",
    useTimeValueArr:["",""],
    useTimeActiveValueArr:["",""],
    modalShow:0
})

const showLimitation = computed(()=>{
    let flag = false
    if(form.value.sendType == 1){
        if(form.value.sendObject == 0){
            if(!form.value.isMemberType){
                flag = true
            }else{
                flag = false
            }
        }else{
           if(form.value.sendObject != 2 ){
                flag = true
           }
        }
    }else{
        flag = false
    }
    return  flag
})
const showLimitations = computed(()=>{
    return (form.value.sendType == 1 && (form.value.sendObject == 2 || (form.value.sendObject == 0 && form.value.isMemberType)))
})

const sendForm = ref({
    needValue:"1",
    couponList:[]
})
const sendformRef =ref(null)

const activeType = ref("基本信息");
const formInline = ref([

])

const btnLefts = ref([

])
const btnRights = ref([
])

const tableConfig = ref([
    {
      prop: "couponsName",
      label: "优惠券名称",
    },
    {
      prop: "userName",
      label: "会员姓名",
    },
    {
      prop: "phone",
      label: "手机号",
    },
    {
        type: 'slot',
        label: '发放情况',
        prop: 'recordStatus',
        width: 140,
        needHeader: true,
        slotHeaderName: 'statusHeader',
        slotName: 'recordStatus'
    },
    {
      prop: "releaseTime",
      label: "发放时间",
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const seachTable = ref(null);

const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        
        let params = {
            ...formInline,
            id:uuid.value,
            recordStatus:status.value == 0?"":status.value
        }
 
        let result = await releaseDetPage(params);
 
        totalPage.value = Number(result.total);
        tableData.value = result.records;
        tableLoading.value = false;
    }catch(e){
        
        tableLoading.value = false;
    }
}
const status = ref(0);

const handleCommand = (name) => {
    status.value = name;
    seachTable.value.handlerSearch();
};
const levelList = ref([]);
const layerList = ref([]);
const _getMemberLevelList = async ()=>{
    try{
        let result = await getMemberLevelList();
        levelList.value = result;
    }catch(e){
        console.log(e);
    }
}

const _getMemberLayeringList = async ()=>{
    try{
        let result = await getMemberLayeringList();
        layerList.value = result;

    }catch(e){
        console.log(e);
    }
}
const getMemberName = (ids = [])=>{
    let name = levelList.value.filter(value=>{
        return ids.includes(value.id);
    }).map(value=>value.levelName).join("、")
    return name;
}
const getMemberLayer = (ids = [])=>{
    let name = layerList.value.filter(value=>{
        return ids.includes(value.id);
    }).map(value=>value.layeringName).join("、")
    return name;
}
const pageLoading = ref(false);
const uuid = ref(route.query.id || "");
const _getTaskDetail = async ()=>{
    pageLoading.value = true;
    try{
        await _getMemberLevelList()
        await _getMemberLayeringList();
        let result = await getTaskDetail(uuid.value);
        form.value = {

            name:result.taskName,
            remark:result.remark,
            sendType:result.taskType,
            sendObject:result.targetType,
            isMemberType:result.unconsumed == 1?true:false,
            memberLevel:[],
            memberlayer:[],
            memberphone:result.phones,
            sendWay:result.taskDateType,
            useTimeValue:"",
            useTimeValueArr:["",""],
            useTimeActiveValueArr:["",""],
            modalShow:result.showCouponPopup?0:1
        }
        if(form.value.sendObject == 1){
            form.value.memberLevel = result.targetIds;
        }else if(form.value.sendObject == 3){
            form.value.memberlayer = result.targetIds;
        }
        if(form.value.sendType == 0 && form.value.sendWay == 1){
            if(form.value.sendObject != 2){
                form.value.useTimeValue = result.taskStartTime;
            }else{
                form.value.useTimeValueArr = [result.taskStartTime,result.taskEndTime];
            }
        }else if(form.value.sendType == 1){
            form.value.useTimeActiveValueArr = [result.taskStartTime,result.taskEndTime];
        }
        sendForm.value.couponList = result.couponsList.map(lis=>{
            return {
                ...lis,
                id:lis.couponsId,
                sendNum:lis.num,
                maxNum:lis.residualNum
            }
        })
    }catch(e){
        console.log(e);
    }finally{
        pageLoading.value = false;
    }
}
_getTaskDetail();


onActivated(()=>{
    if(uuid.value !== route.query.id){
        uuid.value = route.query.id;
        activeStep.value = 0;
        _getTaskDetail();
    }

})

</script>
<template>
    <div class="page-contain">
        <TopBar :backValue="backValue" :tabName="tabName" ref="topbarRef">
        </TopBar>
        <div class="info-contain" v-loading="pageLoading">
            <div style="width:100%;padding-bottom:10px;">
                <el-radio-group v-model="activeType">
                    <el-radio-button label="基本信息" />
                    <el-radio-button label="活动规则" />
                    <el-radio-button label="发放详情" />
                </el-radio-group>
            </div>
            <div style="width:100%" v-if="activeType == '基本信息'">
                <el-form :model="form" label-width="80px" ref="formRef">
                    <div class="form-contain">
                        <el-form-item label="发放名称：">
                            {{ form.name }}
                        </el-form-item>
                        <el-form-item label="备注名称：">
                            {{ form.remark || "-"}}
                        </el-form-item>
                        <el-form-item label="发放类型：">
                            <span v-if="form.sendType == 0">自动发放</span>
                            <span v-if="form.sendType == 1">主动领取</span>
                        </el-form-item>
                        <el-form-item label="发放对象：">
                            <span v-if="form.sendObject == 0">
                                全部会员({{ form.isMemberType?"未消费会员":"全部" }})
                            </span>
                            <span v-if="form.sendObject == 1">
                                指定会员等级({{ getMemberName(form.memberLevel) }})
                            </span>
                            <span v-if="form.sendObject == 3">
                                指定会员分层({{ getMemberLayer(form.memberlayer) }})
                            </span>
                            <span v-if="form.sendObject == 2">新会员</span>
                            <span v-if="form.sendObject == 4">
                                指定会员({{ form.memberphone }})
                            </span>
                        </el-form-item>
                        <el-form-item label="发放时间：" v-if="form.sendType == 0">
                            <span v-if="form.sendWay == 0">立即发放</span>
                            <span v-if="form.sendWay == 1">
                                <span v-if="form.sendWay == 1 && form.sendObject != 2">{{ form.useTimeValue }}</span>
                                <span v-if="form.sendWay == 1 && form.sendObject == 2">{{ form.useTimeValueArr.join("~")}} </span>
                            </span>
                        </el-form-item>
                        <el-form-item label="弹窗展示：" v-if="form.sendType == 0">
                            <span v-if="form.modalShow == 0">是</span>
                            <span v-if="form.modalShow == 1">否</span>
                        </el-form-item>
                        <el-form-item label="发放时间：" v-if="form.sendType == 1">
                            <span>{{ form.useTimeActiveValueArr.join("~") }}</span>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <div style="width:100%" v-if="activeType == '活动规则'">
                <el-form :model="sendForm" label-width="80px" ref="sendformRef">
                    <el-form-item label="发放内容：">
                        <div style="width:100%;margin-top:8px" v-if="sendForm.couponList && sendForm.couponList.length>0">
                            <el-table :data="sendForm.couponList" style="width: 100%" stripe>
                                <el-table-column prop="couponsName" label="优惠券名称">
                                </el-table-column>
                                <el-table-column prop="sendNum" label="赠券数" v-if="form.sendType == 0">
                                    <template #header>
                                        <div class="info-show">
                                            <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                                                赠券数
                                            </div>
                                            <el-tooltip placement="top">
                                                <template #content>
                                                    <div class="tips-info">
                                                        赠券数：单个发券对象发放数量
                                                    </div>
                                                </template>
                                                <img src="@/assets/images/warning-circle.png" alt="" class="img">
                                            </el-tooltip>

                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="isSendNum" label="是否限制次数" v-if="showLimitation">
                                    <template #="{row,$index}">
                                        <span v-if="!row.limitFlag">不限</span>
                                        <span v-else>限制</span>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="isSendNum" label="每人每天限领" v-if="showLimitation">
                            
                                    <template #="{row,$index}">
                                        <span  v-if="row.limitFlag">{{ row.dayLimitNum }}</span>
                                        <span v-else>-</span>
                                    </template>
                                    
                                </el-table-column>

                                <el-table-column prop="isSendNum" label="发放时间限领" v-if="showLimitation">
                                  
                                    <template #="{row,$index}">
                                        <span  v-if="row.limitFlag">{{ row.totalLimitNum }}</span>
                                        <span v-else>-</span>
                                    </template>
                                </el-table-column>
                                <el-table-column width="136" prop="isSendNum" label="次数（次）" v-if="showLimitations">
                                    <template #="{row,$index}">
                                      <span>{{ row.newVipNum }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="maxNum" label="剩余数量">
                                    
                                </el-table-column>
                                <el-table-column prop="maxNum" label="优惠内容">
                                    <template #default="{ row }">
                                        <div class="info-show">
                                            <div class="text-show" >
                                                满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}
                                                
                                            </div>
                                            <el-tooltip placement="top">
                                                <template #content>
                                                    <div class="tips-info">
                                                    1.优惠内容：满{{ `${ row.thresholdAmount?row.thresholdAmount:'' }` }}减{{ `${ row.discountsAmount?row.discountsAmount:'' }` }}；
                                                    2.适用门店及业务：{{ row.businessScope  == 0?'全部门店及业务':`指定门店及业务` }}；
                                                    3.适用范围：{{ ["全部商品可用","指定商品可用","指定商品不可用"][row.activityScope] }}
                                                    </div>
                                                </template>
                                                <img src="@/assets/images/warning-circle.png" alt="" class="img">
                                            </el-tooltip>

                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-form-item>
                </el-form>

            </div>
            <div style="width:100%;height:calc(100% - 52px)" v-if="activeType == '发放详情'">
                <SeachTable 
                    :tableType="2"
                    :tableWidth="100"
                    ref="seachTable"
                    :forms="formInline"
                    :btnLefts="btnLefts"
                    :btnRights="btnRights"
                    :tableLoading="tableLoading"
                    :tableConfig="tableConfig"
                    :tableData="tableData"
                    :totalPage="totalPage"
                    @handlerSearch="handlerSearch"
                    :showLine="false"
                    :showBtn="false"

                    >
                    <template #recordStatus="{ row }">
                        <span v-if="row.recordStatus == 0">待发送</span>
                        <span v-if="row.recordStatus == 1">成功</span>
                        <span v-if="row.recordStatus == 2">失败</span>
                    </template>
                    <template #statusHeader>
                        <el-dropdown @command="handleCommand">
                            <div class="status-div">
                                发放情况
                                <img src="@/assets/images/shaixuan3.png" alt="">
                            </div>
                            <template #dropdown>
                                <el-dropdown-menu >
            
                                    <el-dropdown-item :command="1">成功</el-dropdown-item>
                                    <el-dropdown-item :command="2">失败</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </SeachTable>
            </div>
        </div>
    </div>

</template>
<style lang="less" scoped>
:deep(.el-table__header){
    tr{
        th{
            .cell{
                border-right: 0px;
            }
        }
    }
}
.tips-info{
    max-width: 300px; 
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
        
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}
:deep(.el-table__row){
    .el-input .el-input__wrapper{
        background: rgba(0,0,0,0);
    }
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}
:deep(.el-table__inner-wrapper::before){
    width: 0;
}
.status-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color:#000;
    position: relative;
    top:3px;
    img{
        width: 14px;
        height: 14px;
        cursor: pointer;
        margin-left:4px;
    }
}
.page{
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  margin-top:8px;
}
:deep(.el-table__inner-wrapper::before){
    display:none;
}
:deep(.el-table th.el-table__cell){
    background: #EBEBEB;
}

:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
.inline-class{
    display: flex;
    justify-content: flex-start;
    align-items: center;
}
.unit-class{
    font-size: 14px;
    color: #000000;
    font-weight: 400;
    line-height: 32px;
    margin-left:8px;
}
.form-contain{
    width: 100%;

}
.page-contain{
    width: 100%;
    height: 100%;
}
.info-contain{
    width: 100%;
    height: calc(100% - 48px);
    box-sizing: border-box;
    padding:16px 24px;
    :deep(.el-form-item){
        margin-bottom:0;
    }
    :deep(.el-form-item__label){
        padding:0;
    }
}

:deep(.el-radio-button:first-child .el-radio-button__inner) {
  border-left: 1px solid #3480FF;
}
:deep(.el-table__header){
    tr{
        th{
            &:last-child{
                .cell{
                    border-right: 0px;
                }
            }
        }
    }
}
:deep(.search-line){
    padding:0;
}
:deep(.search-table .table){
    padding:0;
    padding-top:12px;
}
:deep(.search-table .btn-area){
    padding:0;

}
</style>